package com.atguigu.gulimail.product.exception;

import com.atguigu.common.exception.BizCodeNum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author sourire
 * @version 1.0
 * @date 2020/5/27 15:26
 */
@Slf4j
@RestControllerAdvice(basePackages={"com.atguigu.gulimail.product.controller"})
public class GulimailControllerAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handlerValidException(MethodArgumentNotValidException e){
        log.error("参数校验错误:{},异常类型：{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        result.getFieldErrors().forEach(item->{
            map.put(item.getField(), item.getDefaultMessage());
        });
        return R.error(BizCodeNum.VALID_EXCEPTION.getCode(), BizCodeNum.VALID_EXCEPTION.getMsg()).put("data", map);
    }

    @ExceptionHandler(Throwable.class)
    public R handlerException(Exception e){
        log.error("出现未知异常:{}",e.getMessage());
        return R.error(BizCodeNum.UNKNOW_EXCEPTION.getCode(), BizCodeNum.UNKNOW_EXCEPTION.getMsg());
    }
}
